#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include <vector>
#include <memory>
#include <sstream>
#include <functional>
#include <sys/types.h>
#include <unordered_map>
#include "Common.hpp"
#include "Logger.hpp"

const std::string Sep = "\r\n";
const std::string LineSep = " ";
const std::string HeaderLineSep = ": ";
const std::string BlankLine = Sep;
const std::string http_version = "HTTP/1.0";
const std::string defaulthomepage = "wwwroot/";
const std::string page404 = "wwwroot/404.html";
const std::string firstpage = "index.html";

using namespace LogMudule;
class HttpRequest
{
public:
    HttpRequest() = default;
    ~HttpRequest() = default;
    bool ParseHeaderkv()
    {
        std::string key, value;
        for (auto &header : _req_header)
        {
            // Connection: keep-alive
            if (SplitString(header, HeaderLineSep, &key, &value))
            {
                _headerkv.insert(std::make_pair(key, value));
            }
        }
        return true;
    }
    bool IsArgs()
    {
        return _isexec;
    }
    std::string Path()
    {
        return _path;
    }
    std::string Args()
    {
        return _args;
    }
    void ParseHeader(std::string &request_str)
    {
        std::string line;
        while (true)
        {
            bool r = ParseOneLine(request_str, &line, Sep);
            if (r && !line.empty())
            {
                _req_header.push_back(line);
            }
            else if (r && line.empty())
            {
                _blank_line = Sep;
                break;
            }
            else
            {
                return;
            }
        }
        ParseHeaderkv();
    }
    void Deserialize(std::string &request_str)
    {
        if (ParseOneLine(request_str, &_req_line, Sep))
        {
            ParseReqLine(_req_line, LineSep);
            ParseHeader(request_str);
            _body = request_str;
        }
        if(_method == "POST")
        {
            _isexec = true;
            _path = _uri;
            _args = _body;
        }
        else if(_method == "GET")
        {
            auto it = _uri.find('?');
            if(it != std::string::npos)
            {
                _isexec = true;
                _path = _uri.substr(0, it);
                _args = _uri.substr(it + 1);
            }

        } 
    }
    void Print()
    {
        std::cout << "_method: " << _method << std::endl;
        std::cout << "_uri: " << _uri << std::endl;
        std::cout << "_version: " << _version << std::endl;

        for (auto &kv : _headerkv)
        {
            std::cout << kv.first << " # " << kv.second << std::endl;
        }
        std::cout << "_blank_line: " << _blank_line << std::endl;
        std::cout << "_body: " << _body << std::endl;
    }
    std::string GetContent(std::string path)
    {
        // 暂时做法
        // std::string content;
        // std::ifstream in(path);
        // if (!in.is_open())
        //     return std::string();
        // std::string line;
        // while (std::getline(in, line))
        // {
        //     content += line;
        // }
        // in.close();
        // return content;
        std::string content;
        std::ifstream in(path, std::ios::binary);
        if (!in.is_open())
            return std::string();
        in.seekg(0, std::ios::end);
        size_t size = in.tellg();
        in.seekg(0, std::ios::beg);
        content.resize(size);
        in.read((char *)content.c_str(), size);
        return content;
    }
    std::string Uri()
    {
        return _uri;
    }
    std::string Suffix()
    {
        auto pos = _uri.rfind('.');
        if (pos == std::string::npos)
            return std::string(".html");
        return _uri.substr(pos);
    }

private:
    void ParseReqLine(std::string &_req_line, const std::string sep)
    {
        (void)sep;
        std::stringstream ss(_req_line);
        ss >> _method >> _uri >> _version;
    }

    std::string _req_line;
    std::vector<std::string> _req_header;
    std::string _blank_line;
    std::string _body; // body内部可能会包含参数

    // 在反序列化的过程中，细化我们解析出来的字段
    std::string _method;
    std::string _uri; // 用户想要这个 // /login.html || /login?xxxxx
    std::string _path;
    std::string _args;
    std::string _version;
    std::unordered_map<std::string, std::string> _headerkv;
    bool _isexec = false;
};
class HttpResponse
{
public:
    HttpResponse() : _verion(http_version), _blank_line(Sep)
    {
    }
    ~HttpResponse() = default;
    // 构建应答
    void Build(HttpRequest &req)
    {
        std::string uri = defaulthomepage + req.Uri(); // wwwroot/   wwwroot/a/b/
        if (uri.back() == '/')
        {
            uri += firstpage; // wwwroot/index.html
        }
        LOG(LogLevel::DEBUG) << "------客户端在请求: " << req.Uri();
        req.Print();
        LOG(LogLevel::DEBUG) << "----------------------------";

        _content = req.GetContent(uri);
        if (_content.empty())
        {
            // 用户请求的资源并不存在
            _status_code = 404;
            _content = req.GetContent(page404);
        }
        else
        {
            _status_code = 200;
        }

        _status_desc = Code2Desc(_status_code); // 和状态码是强相关的！
        if (!_content.empty())
        {
            SetHeader("Content-Length", std::to_string(_content.size()));
        }
        std::string mime_type = Suffix2Desc(req.Suffix());

        SetHeader("Content-Type", mime_type);
        _body = _content;
    }
    void SetCode(int code)
    {
        _status_code = code;
        _status_desc = Code2Desc(code);
    }

    void SetHeader(const std::string &key, const std::string &value)
    {
        _header_kv[key] = value;
    }
    void SetBody(std::string &body)
    {
        _body = body;
    }

    void Serialize(std::string *resp_str)
    {
        // 填充要素
        for (auto &header : _header_kv)
        {
            std::string header_line = header.first + HeaderLineSep + header.second;
            _resp_header.push_back(header_line);
        }
        _resp_line = _verion + LineSep + std::to_string(_status_code) + LineSep + _status_desc + Sep;

        // 拼接
        *resp_str = _resp_line;
        for (auto &header : _resp_header)
        {
            *resp_str += header + Sep;
        }
        *resp_str += _blank_line;
        *resp_str += _body;
    }

private:
    std::string Suffix2Desc(const std::string &suffix)
    {
        if (suffix == ".html")
            return "text/html";
        else if (suffix == ".css")
            return "text/css";
        else if (suffix == ".js")
            return "application/javascript";
        else if (suffix == ".jpg" || suffix == ".jpeg")
            return "image/jpeg";
        else if (suffix == ".png")
            return "image/png";
        else if (suffix == ".gif")
            return "image/gif";
        else
            return "text/plain";
    }
    std::string Code2Desc(int code)
    {
        switch (code)
        {
        case 200:
            return "OK";
        case 404:
            return "Not Found";
        case 301:
            return "Moved Permanently";
        case 302:
            return "Found";
        default:
            return std::string();
        }
    }
    // 必备的要素
    std::string _verion;
    int _status_code;
    std::string _status_desc;
    std::string _content;
    std::unordered_map<std::string, std::string> _header_kv;

    // 构建应答
    std::string _resp_line;
    std::vector<std::string> _resp_header;
    std::string _blank_line;
    std::string _body;
};